package ch.nostromo.tiffanys.clients.xboard.xbif;

import ch.nostromo.tiffanys.game.board.BoardTools;
import ch.nostromo.tiffanys.game.move.Move;
import ch.nostromo.tiffanys.game.move.MoveInput;
import ch.nostromo.tiffanys.lib.ChessTools;

public class XBoardMove {

  public static String tiff2XBoard(Move move) {
    String result;
    if (move.isCastlingShort()) {
      result = "O-O";
    } else if (move.isCastlingLong()) {
      result = "O-O-O";
    } else {
      result = move.getFrom();
      result += move.getTo();
      if (move.isPromotion()) {
        result += ChessTools.getPieceDescriptionByCode(move.getPromotion());
      }
    }
    return result;
  }

  public static MoveInput xBoard2Tiff(String move) throws XBoardMoveParsingException {
    try {
      String froms = move.substring(0, 2);
      String tos = move.substring(2, 4);

      MoveInput toMove;
      if (move.length() > 4) {
        int pieceCode = BoardTools.getPieceCodeByDescription(move.substring(4));
        toMove = new MoveInput(froms, tos, pieceCode);
      } else {
        toMove = new MoveInput(froms, tos);
      }
      
      return toMove;
    } catch (Throwable e) {
      throw new XBoardMoveParsingException("Unable to parse XBoard (move) command: " + move + " " + e.getMessage());
    }
  }

}
